import { Toast } from 'antd-mobile';
import { getUserInfo } from './login'
import { reqdetail, reqcaradd } from '../../request/api';

//状态
const initState = {
    goodsinfo: {},
    visible: false,//弹窗是否显示
    num: 1,//数量
    arr: ['商品', '评价', '详情', '推荐']
}

//actionType
const TYPES = {
    DETAIL_CHANGE_GOODSINFO: 'DETAIL_CHANGE_GOODSINFO',
    DETAIL_CHANGE_VISIBLE: 'DETAIL_CHANGE_VISIBLE',
    DETAIL_CHANGE_NUM: 'DETAIL_CHANGE_NUM'
}

//修改state reducer 
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.DETAIL_CHANGE_GOODSINFO:
            return {
                ...state,
                goodsinfo: action.goodsinfo
            }
        case TYPES.DETAIL_CHANGE_VISIBLE:
            return {
                ...state,
                visible: action.visible
            }
        case TYPES.DETAIL_CHANGE_NUM:
            return {
                ...state,
                num: action.num
            }
        default:
            return state;
    }
}

//做逻辑和异步的acitons actionCreators
export const actions = {
    changeInfo: goodsinfo => ({ type: TYPES.DETAIL_CHANGE_GOODSINFO, goodsinfo }),
    requestInfo: (id) => {
        return (dispatch, getState) => {
            reqdetail({ id }).then(res => {
                if (res.data.code == 200) {
                    dispatch(actions.changeInfo(res.data.list[0]))
                }
            })
        }
    },
    changeVisible: visible => ({ type: TYPES.DETAIL_CHANGE_VISIBLE, visible }),
    changeNum: num => {
        return (dispatch, getState) => {
            if (num <= 1) {
                Toast.show({
                    content: '至少添加1件'
                })
            }
            dispatch({ type: TYPES.DETAIL_CHANGE_NUM, num })
        }
    },
    requestAddcart: (type) => {
        return (dispatch, getState) => {
            let userInfo = getUserInfo(getState());
            let info = getGoodsinfo(getState());
            let num = getNum(getState());

            reqcaradd({
                uid: userInfo.uid,
                goodsid: info.id,
                num,
                type
            }).then(res => {
                if (res.data.code == 200) {
                    Toast.show({
                        content: res.data.msg
                    })
                    dispatch(actions.changeVisible(false))
                }
            })
        }
    }
}

//导出数据 Selectors 
export const getGoodsinfo = state => state.detail.goodsinfo;

export const getVisible = (state) => state.detail.visible;

export const getNum = (state) => state.detail.num;

export const getArr = state => state.detail.arr;
//导出reducer 
export default reducer;